import redis
import json
from .DbOprate import DbOprate
# Redis配置


REDIS_CONFIG = {
    'host': '127.0.0.1',
    'port': 6379,
    'password': 'job',  # 如果没有密码就设置为None
    'db': 3,
    'decode_responses': True,
    'socket_connect_timeout': 5,
    'socket_timeout': 5
}
'''
REDIS_CONFIG = {
    'host': '172.30.168.43',
    'port': 6379,
    'password': 'deli',  # 如果没有密码就设置为None
    'db': 3,
    'decode_responses': True,
    'socket_connect_timeout': 5,
    'socket_timeout': 5
}
'''
class FactorDataManager:
    """因子数据管理器 - 处理数据库和Redis的因子数据存取"""
    
    def __init__(self, stock_code, redis_config=None):
        self.stock_code = stock_code
        self.redis_config = redis_config or REDIS_CONFIG
        self.redis_prefix = f"factor_data:{stock_code}"
        
        # 初始化Redis连接
        self._init_redis()
        
    def _init_redis(self):
        """初始化Redis连接"""
        try:
            # 构建Redis连接参数
            redis_params = {
                'host': self.redis_config['host'],
                'port': self.redis_config['port'],
                'db': self.redis_config['db'],
                'decode_responses': self.redis_config['decode_responses'],
                'socket_connect_timeout': self.redis_config['socket_connect_timeout'],
                'socket_timeout': self.redis_config['socket_timeout']
            }
            
            # 如果有密码则添加密码参数
            if self.redis_config['password']:
                redis_params['password'] = self.redis_config['password']
            
            self.redis_client = redis.Redis(**redis_params)
            
            # 测试连接
            self.redis_client.ping()
            print(f"Redis连接成功: {self.redis_config['host']}:{self.redis_config['port']}")
        except Exception as e:
            print(f"Redis连接失败: {e}")
            self.redis_client = None
        
    def save_factor_to_db(self, trade_date, factor_key, factor_val):
        """保存因子数据到数据库"""
        try:
            # 先检查是否已存在
            check_sql = """
            SELECT id FROM stock_factor_data 
            WHERE ts_code = %s AND trade_date = %s AND factor_key = %s
            """
            existing = DbOprate.fetchall(check_sql, (self.stock_code, trade_date, factor_key))
            
            if existing:
                # 更新已存在的记录
                update_sql = """
                UPDATE stock_factor_data 
                SET factor_val = %s 
                WHERE ts_code = %s AND trade_date = %s AND factor_key = %s
                """
                DbOprate.execute(update_sql, (factor_val, self.stock_code, trade_date, factor_key))
            else:
                # 插入新记录
                insert_sql = """
                INSERT INTO stock_factor_data (ts_code, trade_date, factor_key, factor_val)
                VALUES (%s, %s, %s, %s)
                """
                DbOprate.execute(insert_sql, (self.stock_code, trade_date, factor_key, factor_val))
        except Exception as e:
            print(f"保存因子数据失败: {e}")
            
    def load_factors_to_redis(self):
        """将数据库中的因子数据加载到Redis"""
        try:
            sql = """
            SELECT trade_date, factor_key, factor_val 
            FROM stock_factor_data 
            WHERE ts_code = %s
            ORDER BY trade_date
            """
            results = DbOprate.fetchall(sql, (self.stock_code,))
            
            # 清空旧的缓存
            #keys = self.redis_client.keys(f"{self.redis_prefix}:*")
            #if keys:
            #    self.redis_client.delete(*keys)
            
            # 加载到Redis
            for row in results:
                trade_date, factor_key, factor_val = row
                redis_key = f"{self.redis_prefix}:{trade_date}:{factor_key}"
                self.redis_client.set(redis_key, factor_val)
            self.redis_client.set("Jackson", "hello")
            print(f"已将 {len(results)} 条因子数据加载到Redis")
            return len(results)
        except Exception as e:
            print(f"加载因子数据到Redis失败: {e}")
            return 0
            
    def get_factor_from_redis(self, trade_date, factor_key):

        """从Redis获取因子值"""
        try:
            redis_key = "factor_data:" + str(self.stock_code) + ":" + str(trade_date) + ":" + str(factor_key)
            # 先检查当前数据库有哪些key
            value = self.redis_client.get(redis_key)
            print(f"[DEBUG] {redis_key} 获取到的value: {value}")
            return value
        except Exception as e:
            print(f"从Redis获取因子失败: {e}")
            import traceback
            traceback.print_exc()
            return None
            
    def save_factor_to_redis(self, trade_date, factor_key, factor_val):
        """保存因子值到Redis"""
        try:
            redis_key = f"{self.redis_prefix}:{trade_date}:{factor_key}"
            self.redis_client.set(redis_key, str(factor_val))
        except Exception as e:
            print(f"保存因子到Redis失败: {e}")